package com.wallet.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wallet.constants.BusinessConstants;
import com.wallet.mappers.WalletDetailsMapper;
import com.wallet.entity.WalletDetailsEntity;
import com.wallet.service.WalletDetailsService;
import com.wallet.util.DateUtil;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
/**
 * 钱包流水服务接口实现
 * @author zhangguangyuang
 */
@Service
public class WalletDetailsServiceImpl  extends ServiceImpl<WalletDetailsMapper, WalletDetailsEntity> implements WalletDetailsService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Resource
    private WalletDetailsMapper walletDetailsMapper;

    @Override
    public boolean isExistOrderNoAndTradeNo(String orderNo, String outTradeNo) {
        return walletDetailsMapper.isExistOrderNoAndTradeNo(orderNo,outTradeNo) > 0 ? true : false;
    }

    public List<WalletDetailsEntity> getWalletDetailsByWalletIdAndStartTimeAndEndTime(Integer walletId,String startTime,String endTime) {
        if(StringUtils.isBlank(startTime) && StringUtils.isBlank(endTime)){
            //如果当前时间和结束时间为空，查询结果为当前月第一天到当前时间
            startTime = DateUtil.getFirstDay();
            endTime = DateUtil.getDate();
        }
        List<WalletDetailsEntity> walletDetailsEntities = walletDetailsMapper.getWalletDetailsByWalletIdAndStartTimeAndEndTime(walletId,startTime,endTime);
        //存到redis缓存，修改后更新缓存
        if(!redisTemplate.opsForHash().hasKey(BusinessConstants.WALLET_DETAILS_PREFIX,String.valueOf(walletId))){
            String json = JSON.toJSONString(walletDetailsEntities);
            redisTemplate.opsForHash().put(BusinessConstants.WALLET_DETAILS_PREFIX,String.valueOf(walletId),json);
        }else{
            String json = (String)redisTemplate.opsForHash().get(BusinessConstants.WALLET_DETAILS_PREFIX,String.valueOf(walletId));
            walletDetailsEntities = JSON.parseArray(json, WalletDetailsEntity.class);
        }
        return walletDetailsEntities;
    }

}
